import React, { createRef, forwardRef, useEffect, useImperativeHandle, useState, useRef } from "react";
import { BackHandler, Image, StyleSheet, Text } from "react-native";
import { commonStyles } from "../../configs/commonStyle";
import { TouchableOpacity, View } from "react-native-ui-lib";
import { IconImage } from "../../utils";
import RNFetchBlob from "rn-fetch-blob";
import AudioRecorderPlayer, {
  AudioEncoderAndroidType,
  AudioSourceAndroidType,
  AVEncoderAudioQualityIOSType,
  AVEncodingOption,
} from "react-native-audio-recorder-player";
import { userStore } from "../../store";
import { toJS } from "mobx";
import moment from "moment";
import ToastUtils from "../../utils/ToastUtils";
import RecordSurveyDialog from "../common/dialog/RecordSurveyDialog";
import Events from "../../utils/events";
import OkDialog from "../common/OkDialog";
import { uploadError } from "../../utils/util";

/**
 * 录音
 * @param orderNo
 * @param onRef
 * @param recordComplete
 * @returns {JSX.Element}
 * @constructor
 */
const Recorder = ({ onRef, showRecorder },ref) => {
  const [recordTime, setRecordTime] = useState("00:00:00");
  const [isRecording, setIsRecording] = useState(true);
  const audioRecorderPlayer = new AudioRecorderPlayer();
  let timeLong = 0;
  let times = 0;
  const okDialog = createRef();
  const recordSurveyDialog = useRef();

  useEffect(() => {
    logger("触发录音", showRecorder);
    if (showRecorder == true) {
      onStartRecord();
    }
  }, [showRecorder]);

  useEffect(() => {
    BackHandler.addEventListener('hardwareBackPress',  onBackAndroid);
    return ()=>{
      BackHandler.removeEventListener('hardwareBackPress',  onBackAndroid);
    }
  }, []);

  const onBackAndroid=()=>{
    logger('监听返回')
    ToastUtils.showInfo('请先停止录音')
    return true;
  }

  useImperativeHandle(onRef, () => ({
    startRecord: () => {
      // onStartRecord();
    },
  }));


  const onStartRecord = async () => {
    const path = Platform.select({
      ios: `${+new Date()}.m4a`,
      android: `${RNFetchBlob.fs.dirs.CacheDir}/${+new Date()}.mp3`,
    });
    const result = await audioRecorderPlayer.startRecorder(path, {
      AudioEncoderAndroid: AudioEncoderAndroidType.AAC,
      AudioSourceAndroid: AudioSourceAndroidType.MIC,
      AVSampleRateKeyIOS: 8000,
      AudioSamplingRateAndroid: 8000,
      AudioEncodingBitRateAndroid: 32000,
      AVEncoderAudioQualityKeyIOS: AVEncoderAudioQualityIOSType.min,
      AVNumberOfChannelsKeyIOS: 2,
      AVFormatIDKeyIOS: AVEncodingOption.aac,
    });
    logger("调用录音", result);
    audioRecorderPlayer.addRecordBackListener((e) => {
      logger("录音时间",times,timeLong, e.currentPosition);
      if(timeLong>0&&timeLong == e.currentPosition)
      {
        if(times>=2)
        {
          //2次时间戳都相同，则暂停
          onPauseRecord();
        }
        times++;
        return;
      }
      timeLong = e.currentPosition;
      setRecordTime(audioRecorderPlayer.mmssss(
        Math.floor(e.currentPosition),
      ));
      if (e.currentPosition >= 1000 * 60 * 20) {
        openSurveyDialog()
        stopRecord();
        logger("录音超过20分，自动停止");
      }
    });
    logger("开始录音", result);
  };

  const openSurveyDialog = () => {
    audioRecorderPlayer.pauseRecorder()
    recordSurveyDialog.current.show()
  }

  const cancelSurvey = () => {
    audioRecorderPlayer.resumeRecorder()
  }

  const onStopRecord = React.useCallback(async (data) => {
    logger("停止录音1");
    const result = await audioRecorderPlayer.stopRecorder();
    audioRecorderPlayer.removeRecordBackListener();
    logger("停止录音", timeLong, result);
    const store=Object.assign({}, userStore)
    if(!IsNullOrEmpty(result)&&result!='Already stopped' && typeof result == 'string')
    {

      const list = toJS(store.uploadFailList) || [];
      list.push({
        videoUri:result,
        recordingNo:store.recordingNo,
        distributorId: store.userInfo.distributorId,
        day: moment().format("YYYY-MM-DD HH:mm:ss"),
        track_length:parseInt(timeLong/1000),
        isDance: data.isDance,
        orderService: JSON.stringify({"ser": data.services.map(item => item.text).join(',')})
      });

      userStore.setValue("recordingNo", "");
      userStore.setValue("showRecorder", false);
      userStore.setValue("uploadFailList", list);
      ToastUtils.showSuccessInfo("录音成功");
      Events.publish("UPLOAD_RECORD");
    }
    else{
      userStore.setValue("recordingNo", "");
      userStore.setValue("showRecorder", false);
      okDialog.current.show('录音保存失败,请重新录音')
      uploadError(`录音保存失败：${store.recordingNo}`,`录音保存失败,请重新录音:${result}`)
    }
  }, []);

  const onPauseRecord = React.useCallback(async () => {
    logger("暂停录音2");
    await audioRecorderPlayer.pauseRecorder();
    setIsRecording(false);
  }, []);

  const onResumeRecord = React.useCallback(async () => {
    logger("恢复录音");
    await audioRecorderPlayer.resumeRecorder();
    setIsRecording(true);
  }, []);

  return (
    <View useSafeArea style={styles.container}>
      <View style={styles.recorderWrap}>
        <Text style={commonStyles.text_white_14}> {moment().format("YYYY年MM月DD")}</Text>
        <Text style={{ ...commonStyles.text_white_12, marginTop: 5 }}> {recordTime}</Text>
        {
          isRecording?<Image source={IconImage.audio} style={{ height: 55, width: "98%" }} />:null
        }
        <View row center marginT-20>
          {
            isRecording ? null
              :
              <TouchableOpacity centerH activeOpacity={1} onPress={()=>onResumeRecord()}>
                <Image source={IconImage.btn_record} style={{ width: 43, height: 43,marginRight:20 }} />
              </TouchableOpacity>
          }
          <TouchableOpacity activeOpacity={1} style={styles.button}
                            onPress={() => openSurveyDialog()}>
            <Image source={IconImage.btn_stop} style={{ width: 43, height: 43 }} />
          </TouchableOpacity>
          <OkDialog ref={okDialog} ok={'知道了'} />
          <RecordSurveyDialog ref={recordSurveyDialog} callBack={(data) => onStopRecord(data)} cancalClick={() => cancelSurvey()} />
        </View>
      </View>
    </View>
  );
};

export default forwardRef(Recorder);

const styles = StyleSheet.create({
  recorderWrap: {
    backgroundColor: "black",
    paddingVertical: 20,
    paddingHorizontal: 15,
    justifyContent: "center",
    alignItems: "center",
  },
  container: {
    ...StyleSheet.absoluteFill,
    backgroundColor: "#00000080",
    justifyContent: "flex-end",
  },
});
